package com.hzwq.demo.Login.service;

import com.hzwq.demo.Login.bo.SdteUser;
import com.hzwq.demo.Login.repository.SdteUserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SdteUserService implements ISdteUserService{
    @Autowired
    private SdteUserRepository sdteUserRepository;

    public SdteUser queryUser(String userId,String password){
        SdteUser su = sdteUserRepository.findUser(userId);
        if(su !=null){
            if(su.getLoginPwd().equals(password)){
                return  su;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 根据用户id查询用户对象
     */
    public SdteUser queryUserById(long userId){
        SdteUser user = sdteUserRepository.findUserById(userId);
        return user;
    }

    /**
     * 查询用户列表
     */
    public List<SdteUser> getUserList(SdteUser user){
        List<SdteUser> list = sdteUserRepository.findAll(new Specification<SdteUser>() {
            @Override
            public Predicate toPredicate(Root<SdteUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // build query condition
                List<Predicate> predicates = new ArrayList<Predicate>();
                if(user.getUserName() != null && StringUtils.isNotBlank((String) user.getUserName())){
                    predicates.add(cb.like(root.get("userName").as(String.class), "%"+(String)user.getUserName()+"%"));
                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        });
        return list;
    }

    /**
     * 新增用户
     */
    public SdteUser addUser(SdteUser user){
        return sdteUserRepository.save(user);
    }

    /**
     * 删除用户
     */
    public void deleteUser(long userId){
        sdteUserRepository.deleteById(userId);
    }
}
